# @Version        : 1.0
# @Update Time    : 2025/3/18 21:15
# @File           : dept_service.py
# @IDE            : PyCharm
# @Desc           : 文件描述信息
from advanced_alchemy import service, filters
from sqlalchemy import and_, func

from src import models
from src.crud.dept_repository import DeptRepo
from src.schemas import DeptCreate, DeptUpdate


class DeptService(service.SQLAlchemyAsyncRepositoryService[models.SysDept, DeptRepo]):
    repository_type = DeptRepo
    count_with_window_function = True

    async def get_dept_and_children(self, dept_id: int) -> set[int]:
        """
        获取部门及其子部门
        :param dept_id: 部门id
        :return: 部门id集合
        """
        dept_ids = await super().list(
            and_(
                func.find_in_set(dept_id, models.SysDept.ancestors),
                models.SysDept.status == "1",
            )
        )
        dept_ids = {d.id for d in dept_ids}
        dept_ids.add(dept_id)
        return dept_ids

    # 创建部门
    async def create_dept(self, dept: DeptCreate):
        if dept.parent_id == 0:
            dept.ancestors = "0"
        else:
            parent_dept = await super().get_one(
                and_(models.SysDept.id == dept.parent_id)
            )
            dept.ancestors = f"{parent_dept.ancestors},{dept.parent_id}"
        return await super().create(dept, auto_commit=True)

    async def update_dept(self, dept: DeptUpdate):
        if dept.parent_id is None:
            dept.ancestors = "0"
        else:
            parent_dept = await super().get_one(
                and_(models.SysDept.id == dept.parent_id)
            )
            dept.ancestors = f"{parent_dept.ancestors},{dept.parent_id}"
        await super().update(dept, auto_commit=True)
